<template>
    <el-dialog :close-on-click-modal="false"  ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="50%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-form-item label="养殖设施" prop="facilityId">
                <el-select v-model="ruleForm.facilityId" class="w100p" placeholder="请选择养殖设施" @change="getFacilityName">
                    <el-option v-for="(item, index) in facilityList" :key="index" :label="item.facilityName"
                        :value="item.facilityId" />
                </el-select>
            </el-form-item>
            <el-form-item label="选择批次" prop="batchId">
                <el-select v-model="ruleForm.batchId" class="w100p" placeholder="请选择批次" @change="getBatchName">
                    <el-option v-if="ruleForm.facilityId == item.facilityId && item.status == 'SEALED_POND'"
                        v-for="(item, index) in batchList" :key="index" :value="item.batchId" :label="item.batchName" />
                </el-select>
            </el-form-item>
            <el-form-item label="估产品种" prop="plantVarietyId">
                <el-select v-model="ruleForm.plantVarietyId" class="w100p" placeholder="请选择品种"
                    @change="handleChangeVariety">
                    <el-option v-if="plantVarietyIdList.includes(v.plantVarietyId)" v-for="v, index in varietyList" :key="index" :label="v.plantVarietyName"
                        :value="v.plantVarietyId"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="估产百分比" class="50%" v-show="ruleForm.minRate">
                <span>{{ `${ruleForm.minRate}%~${ruleForm.maxRate}%` }}</span>
            </el-form-item>
            <el-form-item label="系统计算重量" class="50%" v-show="ruleForm.minRate">
                <span>{{ `${ruleForm.minWeight}斤~${ruleForm.minWeight}斤` }}</span>
            </el-form-item>
            <el-form-item label="估产重量" prop="predictWeight">
                <el-input type="number" v-model="ruleForm.predictWeight" class="w100p" clearable placeholder="请输入重量">
                    <template slot="append">斤</template>
                </el-input>
            </el-form-item>
            <el-form-item label="操作人" prop="staffId">
                <el-select v-model="ruleForm.staffId" class="w100p" placeholder="请选择操作人" @change="handleChangePerson">
                    <el-option v-for="item, index in person" :key="index" :label="item.person.name"
                        :value="item.person.personNo"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="估产日期" prop="predictDate">
                <el-date-picker v-model="ruleForm.predictDate" align="right" value-format="yyyy-MM-dd" type="date"
                    placeholder="选择日期" :picker-options="pickerOptions">
                </el-date-picker>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import traditionAssessManagementDS from '@/api/assessManagement/traditionAssessManagementDS.js';
import pondInformationManagement from '@/api/pondManagment/pondInformationManagement.js';
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        batchList: {
            type: Array,
            default: () => {
                return []
            }
        },
        varietyList: {
            type: Array,
            default: () => {
                return []
            }
        },
        facilityList: {
            type: Array,
            default: () => {
                return []
            }
        }
    },
    data() {
        let validatorWeight = function (rule, value, callback) {
            if (value > 0) {
                callback()
            } else {
                callback(new Error('请输入大于0的数值！'))
            }
        }
        return {
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            plantVarietyIdList: [],
            rules: {
                facilityId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                batchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择估产人', trigger: 'change' }
                ],
                predictDate: [
                    { required: true, message: '请选择日期', trigger: 'change' }
                ],
                predictWeight: [
                    { required: true, validator: validatorWeight, trigger: 'change' }
                ],
                plantVarietyId: [
                    { required: true, message: '请选择品种', trigger: 'change' }
                ],
            }
        }
    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    computed: {
        person() {
            return this.$store.state.initData.person || [];
        },
    },
    mounted() { },
    methods: {
        async generateHangingBreedPredictYield(id) {
            traditionAssessManagementDS.generateHangingBreedPredictYield(id).then(res => {
                if (res.code == 1) {
                    this.$set(this.ruleForm, 'maxRate', res.data.maxRate)
                    this.$set(this.ruleForm, 'minRate', res.data.minRate)
                    this.$set(this.ruleForm, 'maxWeight', res.data.maxWeight)
                    this.$set(this.ruleForm, 'minWeight', res.data.minWeight)
                    if (!res.data.maxRate) {
                        this.$message.warning('该批次未配置估产比，请去基础信息中配置估产比')
                    }
                }
            }).catch(err => {
                        this.$message.warning('查询估产比失败')
                console.log(err)
            })
        },
        getFacilityName() {
            let result = this.facilityList.find(obj => obj.facilityId == this.ruleForm.facilityId);
            console.log(result)
            this.$set(this.ruleForm, 'facilityName', result.facilityName || "");
            this.$set(this.ruleForm, 'batchId', '');
            this.$set(this.ruleForm, 'batchName', '');
            this.$set(this.ruleForm, 'maxRate', '');
            this.$set(this.ruleForm, 'minRate', '');
            this.$set(this.ruleForm, 'maxWeight', '');
            this.$set(this.ruleForm, 'minWeight', '');
        },
        handleChangeVariety() {
            let plantVarietyName = this.$public.foundObject(this.varietyList, 'plantVarietyId', this.ruleForm.plantVarietyId).plantVarietyName || '';
            this.$set(this.ruleForm, 'plantVarietyName', plantVarietyName)
            console.log(plantVarietyName)
        },
        handleChangePerson(id) {
            let row = this.person.find(item => Number(item.person.personNo) == id);
            this.$set(this.ruleForm, 'staffName', row.person.name);
        },
        //通过批次下养殖详情获取品种
        async queryByConditionPondInfo(id) {
            this.plantVarietyIdList = [];
            if (!id) return;
            try {
                const res = await pondInformationManagement.queryByCondition({ batchId: id });
                // 检查返回的状态码  
                if (res.code !== 1 && !res.data) {
                    return; // 如果状态码不是1，直接返回并不做后续处理  
                }
                let data = res.data || [];
                let inputPondDetailList = [];
                data.forEach(item => {
                    console.log(item.inputPondDetailList)
                    if (item.inputPondDetailList && item.inputPondDetailList.length > 0) {
                        inputPondDetailList = inputPondDetailList.concat(item.inputPondDetailList)
                    }
                });
                console.log(inputPondDetailList)
                // 如果inputPondDetailList存在且有数据，则处理数据  
                if (inputPondDetailList.length > 0) {
                    this.plantVarietyIdList = inputPondDetailList.map(item => item.plantVarietyId);
                } else {
                    this.$message.warning('请重新选择批次，该批次无投塘数据！')
                }
                console.log(this.plantVarietyIdList)
            } catch (error) {
                console.log(error);
            }
        },
        getBatchName() {
            let result = this.batchList.find(obj => obj.batchId == this.ruleForm.batchId);
            this.$set(this.ruleForm, 'batchName', result.batchName);
            this.generateHangingBreedPredictYield(this.ruleForm.batchId)
            this.queryByConditionPondInfo(this.ruleForm.batchId)
        },
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.addEditApi = traditionAssessManagementDS.add
                this.addEditName = '添加'
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = {
                    ...this.data,
                    staffId: this.data.personNo || this.data.staffId
                }
                this.addEditApi = traditionAssessManagementDS.edit
                this.addEditName = '编辑';
                this.generateHangingBreedPredictYield(this.data.batchId)
                this.queryByConditionPondInfo(this.data.batchId)
            }
        },
        //提交表单
        submitForm() {
            console.log(this.ruleForm)
            this.$refs.ruleForm.validate((valid) => {
                if (!this.ruleForm.maxRate) {
                    this.$message.warning('该批次未配置估产比，请去基础信息中配置估产比！')
                    return
                }
                if (valid) {
                    this.addEditApi({ ...this.ruleForm }).then(res => {
                        this.cancel();
                        this.$message[res.code == 1 ? 'success' : 'warning'](res.msg || res.code == 1 ? '添加成功' : '添加失败')
                    }).catch(err => {
                        console.log(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.line {
    border-bottom: 1px solid #e6e6e6;
}

.icon {
    font-size: 20px;
    line-height: 29px;
    cursor: pointer;
}

::v-deep .noLabel {
    .el-form-item {
        .label {
            display: none;
        }

        .el-form-item__content {
            margin: 0;
        }
    }
}
</style>